package com.example.demo.advice;

import com.example.demo.entity.BaseResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 异常处理
 *
 * @ClassName: ExceptionHandlerAdvice
 * @Description: 异常处理
 * @author: yuyong
 */
@RestControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResult<String> badRequestException(IllegalArgumentException exception) {
        return new BaseResult<>(HttpStatus.BAD_REQUEST.value(), exception.getMessage(), exception.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResult<String> methodArgumentNotValidException(MethodArgumentNotValidException exception) {
        List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
        StringBuilder errors = new StringBuilder();
        allErrors.forEach(a -> errors.append(a.getDefaultMessage()).append(";"));
        return new BaseResult<>(HttpStatus.BAD_REQUEST.value(), errors.toString(), errors.toString());
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResult<String> exception(Throwable throwable) {
        return new BaseResult<>(HttpStatus.BAD_REQUEST.value(), throwable.getMessage(), throwable.getMessage());
    }

}
